package cn.tjad.tjad2.module.common.pictureselect;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by yanghongbing on 16/4/19.
 */
public abstract class TJBaseAdapter extends BaseAdapter {

    protected Context context;
    protected List data;

    public TJBaseAdapter(Context context, List data) {
        this.context = context;
        this.data = data;
    }

    public void setData(List data) {
        if (this.data == null) {
            this.data = data;
        } else if (this.data != data){
            this.data.clear();
            this.data.addAll(data);
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (data == null) {
            return 0;
        }
        return data.size();
    }

    public List getData() {
        return data;
    }

    @Override
    public Object getItem(int position) {
        if (position >= 0 && position < getCount()) {
            return data.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = getViewHolder(position);
            convertView = viewHolder.getItemView();
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            if (viewHolder.getItemViewType() != getItemViewType(position)) {
                viewHolder = getViewHolder(position);
                convertView = viewHolder.getItemView();
                convertView.setTag(viewHolder);
            }
        }
        if(viewHolder != null){
            viewHolder.setValue(getItem(position), position);
        }
        return convertView;
    }


    public abstract ViewHolder getViewHolder(int position);

}
